package com.homework.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.SQLException;

import com.homework.bean.HomeworkBean;
import com.homework.service.HomeworkService;
import com.homework.util.connDB;
import com.sina.sae.storage.SaeStorage;

public class HomeworkDownloadAction {

	private HomeworkService homeworkService;
	private int homeworkId;
	private String address;
	private String filename;

	public HomeworkDownloadAction() {
		// TODO Auto-generated constructor stub
		homeworkService = new HomeworkService();
	}
	
	public int getHomeworkId() {
		return homeworkId;
	}

	public void setHomeworkId(int homeworkId) {
		this.homeworkId = homeworkId;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
	
	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	/*
	 * 定义一个返回InputStream的方法， 该方法将作为被下载文件的入口， 且需要配置stream类型结果时指定inputName参数，
	 * inputName参数的值就是方法去掉get前缀、首字母小写的字符串
	 */
	public InputStream getTargetFile() throws Exception {
		// ServletContext提供getResourceAsStream()方法
		// 返回指定文件对应的输入流
		filename = getAddress().substring(getAddress().lastIndexOf("/")+1);
		SaeStorage ss = new SaeStorage(connDB.getAccessKey(),connDB.getSecretKey(),connDB.getAppName());
		byte[] temp = ss.read("homework", getAddress());
		InputStream is = new ByteArrayInputStream(temp,0,temp.length);
		return is;
	}

	// 下载作业
	public String homeworkDownload() throws SQLException {
		// homeworkBean
		HomeworkBean homeworkBean = new HomeworkBean();
		homeworkBean.setHomeworkId(String.valueOf(this.getHomeworkId()));

		address = homeworkService.homeworkDownload(homeworkBean);
		
		return "Success";
	}
}
